package org.yty.travelagencyredis.Dao.impl;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.yty.travelagencyredis.Dao.ChatGroupMemberDao;
import org.yty.travelagencyredis.model.Entity.ChatGroupMember;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class ChatGroupMemberDaoImpl implements ChatGroupMemberDao {
    private final StringRedisTemplate redisTemplate;

    @Override
    public List<ChatGroupMember> selectByChatGroupId(String chatGroupId) {
        return this.redisTemplate.opsForHash().values(ChatGroupMember.key)
                .stream().map(item -> JSON.parseObject((String) item, ChatGroupMember.class))
                .filter(item -> item.getChatGroupId().equals(chatGroupId))
                .toList();
    }

    @Override
    public boolean insert(ChatGroupMember chatGroupMember) {
        this.redisTemplate.opsForHash().put(ChatGroupMember.key, chatGroupMember.getId().toString(), JSON.toJSONString(chatGroupMember));
        return true;
    }

    @Override
    public void deleteByChatGroupIdAndChatUserId(String chatGroupId, String chatUserId) {
        this.redisTemplate.opsForHash().values(ChatGroupMember.key)
                .stream().map(item -> JSON.parseObject((String) item, ChatGroupMember.class))
                .filter(item -> item.getChatGroupId().equals(chatGroupId) && item.getChatUserId().equals(chatUserId))
                .forEach(item -> this.redisTemplate.opsForHash().delete(ChatGroupMember.key, item.getId()));
    }

    @Override
    public void deleteByChatGroupId(String chatGroupId) {
        this.redisTemplate.opsForHash().values(ChatGroupMember.key)
                .stream().map(item -> JSON.parseObject((String) item, ChatGroupMember.class))
                .filter(item -> item.getChatGroupId().equals(chatGroupId))
                .forEach(item -> this.redisTemplate.opsForHash().delete(ChatGroupMember.key, item.getId()));
    }

    @Override
    public void deleteByChatUserId(String chatUserId) {
        this.redisTemplate.opsForHash().values(ChatGroupMember.key)
                .stream().map(item -> JSON.parseObject((String) item, ChatGroupMember.class))
                .filter(item -> item.getChatUserId().equals(chatUserId))
                .forEach(item -> this.redisTemplate.opsForHash().delete(ChatGroupMember.key, item.getId()));
    }

}
